﻿/*
 * 设计模式 - 享元模式
 * 目的: 缓存
 */


CacheManager cacheManager = new();
var value = cacheManager.GetOrCreate<Operation1>("Key", () => new() { Name = "init" });
Console.WriteLine(value.Name);
var value2 = cacheManager.GetOrCreate<Operation1>("Key");
Console.WriteLine(value2.Name);

/* 第一次表示将key init 的值存起来了. 第二次表示从缓存中获取的数据 */

interface IOperation
{
    public string Name { get; set; }
}

class Operation1 : IOperation
{
    public string Name { get; set; }
}

class CacheManager
{
    private static Dictionary<string, IOperation> _operations = new();

    public IOperation GetOrCreate<T>(string key, Func<T>? func = default) where T : IOperation, new()
    {
        if (!_operations.ContainsKey(key))
        {
            _operations.Add(key, func is null ? new T() : func());
        }
        return _operations[key];
    }
}
